/**
 * Establish communication between content script and extension script
 * Communication packet
 * - checkoutData:
 * 		+ ticketId: Service Now Change Request ID
 * 		+ files: list of file names using absolute path
 */
var rgxTicket = /CHG\d{7}/;
/**
 * Access local storage for preferences
 */
var storage = chrome.storage.local;
var serverHost = 'localhost';
var serverPort = 8080;

function delegate(){
	jQuery("#cmotool-checkouts-panel").delegate('a.cmotool-checkin', 'click', function(){
		var ticketId = jQuery(this).parents('#cmotool-checkouts-panel').data("ticketId");
		var filename = jQuery(this).data("filename");
		console.log('User chooses: ' + ticketId);
		console.log('... ' + filename);
		busy(true);
		checkinFiles({"ticket":ticketId,"files":[filename]}, function(checkoutData){
			console.log(checkoutData);
			if (checkoutData == null) {
				busy(false);
				return;
			}
			updateTicketCheckoutTable(checkoutData.files);
			busy(false);
		});
	});
	
	jQuery("#cmotool-checkouts-panel").delegate('a.cmotool-checkout', 'click', function(){
		var ticketId = jQuery(this).parents('#cmotool-checkouts-panel').data("ticketId");
		var filename = jQuery(jQuery(this).attr("rel")).val();
		console.log('User chooses: ' + ticketId);
		console.log('... ' + filename);		
		busy(true);
		checkoutFiles({"ticket":ticketId,"files":[filename]},function(checkoutData){
			console.log(checkoutData);
			if (checkoutData == null) {
				busy(false);
				return;
			}
			updateTicketCheckoutTable(checkoutData.files);
			jQuery('#cmotool-new-checkout-filename').val('');
			busy(false);
		});
	});
	
	jQuery("#cmotool-checkouts-panel span.cmotool-sync").click(function(){
		var ticketId = jQuery(this).parents('#cmotool-checkouts-panel').data("ticketId");
		busy(true);
		syncTicket({"ticket":ticketId,"url":document.location.href}, function(checkoutData){
			if (checkoutData == null) {
				busy(false);
				return;
			} else {
				jQuery("#cmotool-checkouts-panel div.cmotool-message").html('Ticket has been synced');
			}
			console.log(checkoutData);
			busy(false);
		});						
	});
	
	jQuery("#cmotool-checkouts-panel span.cmotool-svn-ci").click(function(){
		console.log('Generating svn ci command');
		
		var tokens = ["svn ci"];
		jQuery("#cmotool-checkouts-panel .cmotool-checkouts-list li span").each(function(index) {
			tokens.push($(this).text());
		});
		if (tokens.length > 1)
			jQuery("#cmotool-checkouts-panel div.cmotool-message").html(tokens.join(' '));
		else {
			jQuery("#cmotool-checkouts-panel div.cmotool-message").html('No files to commit');
		}
	});
	
	jQuery("#cmotool-checkouts-panel span.cmotool-trig").click(function(){
		console.log('Generating trig command');
		
		var tokens = ["trig"];
		jQuery("#cmotool-checkouts-panel .cmotool-checkouts-list li span").each(function(index) {
			tokens.push($(this).text());
		});
		if (tokens.length>1) {
			jQuery("#cmotool-checkouts-panel div.cmotool-message").html(tokens.join(' '));
		} else {
			jQuery("#cmotool-checkouts-panel div.cmotool-message").html('No files to trig');
		}
	});
	
}

function updateChangeRequest(ticketId, files) {
	var table = createTicketCheckoutTable(ticketId, files);
	jQuery(".subject:first, .vsplit:first").append(table);
	
	delegate();
}

function createTicketCheckoutTable(ticketId, files, tools) {
	var activeTools = tools || ['sync','svn-ci','trig']; // default config for the toolbar 
	var table = "<style>" +
		"div#cmotool-checkouts-panel {position:relative;border: 1px solid #CCCCCC;margin-bottom: 10px;padding: 5px;}"+
		".cmotool-sync,.cmotool-trig,.cmotool-svn-ci{display:inline-block;width:16px;height:16px;margin-right:3px;background-repeat:none;cursor:pointer}" +
		".cmotool-sync{background-image:url(" + chrome.extension.getURL('data/sync.png') + ")}" +
		".cmotool-trig{background-image:url(" + chrome.extension.getURL('data/trig-beta.png') + ")}" +
		".cmotool-svn-ci{background-image:url(" + chrome.extension.getURL('data/subversion.png') + ")}" +
		".cmotool-loading{position:absolute;display:none;right:0;top:5px;width:48px;height:16px;background:url(" + chrome.extension.getURL('data/loading.gif') + ") no-repeat}" +
		".cmotool-message{margin:10px 0}" +
		".cmotool-checkouts-list{padding-left: 0}" +		
		".cmotool-checkouts-list > li{list-style-position: inside}" +
		".cmotool-checkin{margin-left: 20px;float: right;cursor:pointer}" + 
		".cmotool-checkout{cursor:pointer}" +		
		"</style>";
	table += "<div id='cmotool-checkouts-panel' data-ticket-id='" + ticketId + "'>";
	table += "	<h3>CMO Tool - Checkout Panel</h3>";
	// Config the toolbar
	if (activeTools.indexOf('sync')!=-1)
		table += "<span class='cmotool-sync'></span>";
	if (activeTools.indexOf('svn-ci')!=-1)
		table += "<span class='cmotool-svn-ci'></span>";
	if (activeTools.indexOf('trig')!=-1)
		table += "<span class='cmotool-trig'></span>";
	
	table += "<span class='cmotool-loading'></span>";
	table += "	<div class='cmotool-message'></div>";
	table += "	<ol class='cmotool-checkouts-list'>";
	for(var i=0;i<files.length;i++)
		table += "	<li><span>" + normalizeFilename(files[i]) + "</span><a class='cmotool-checkin' data-filename=" + files[i] + ">Check in</a></li>";
	table += "	</ol>"; // cmotool-checkouts-list
	table += "	<div class='cmotool-new-checkout'>";
	table += "		<span>File:</span> <input id='cmotool-new-checkout-filename' size='60' />";
	table += "		<a class='cmotool-checkout' rel='#cmotool-new-checkout-filename'>Check out</a>";
	table += "	</div>"; // cmotool-new-checkout
	table += "</div>";
	return table;
}

function updateTicketCheckoutTable(files) {
	console.log('Updating checkout table...');
	
	var list = jQuery('#cmotool-checkouts-panel ol.cmotool-checkouts-list').empty();
	var table = '';
	for(var i=0;i<files.length;i++)
		table += "	<li><span>" + normalizeFilename(files[i]) + "</span><a class='cmotool-checkin' data-filename=" + files[i] + ">Check in</a></li>";
	list.html(table);
	
	console.log('Updating checkout table completed');
}

function normalizeFilename(filename) {
	return filename.replace('/home/webuser/site/','');
}

function busy(isBusy){
	if (isBusy)
		jQuery('#cmotool-checkouts-panel .cmotool-loading').show();
	else
		jQuery('#cmotool-checkouts-panel .cmotool-loading').hide();
}
// BUSINESS LOGICS
function checkinFiles(checkinData, callback) {
	console.log('Ticket:' + checkinData.ticket);
	console.log('File:' + checkinData.files[0]);
	// Make sure this is made via POST method with 1 param paths: list of files
	var url = 'http://'+ serverHost +':' + serverPort + '/api/changerequests/' + checkinData.ticket + '/checkin';
	jQuery.post(url, {paths: checkinData.files},
			function (response) {
			  	callback(response);
		  	}, 'json').done(function(){
		  		busy(false);
		  	});
	
}

function checkoutFiles(checkoutData, callback) {
	console.log('Ticket:' + checkoutData.ticket);	
	console.log('Files:' + checkoutData.files.join());
	// Make sure this is made via POST method with 1 param paths: list of files	
	var url = 'http://'+ serverHost +':' + serverPort + '/api/changerequests/' + checkoutData.ticket + '/checkout';
	jQuery.post(url, {paths: checkoutData.files},
			function (response) {
			  	callback(response);
		  	}, 'json').done(function(){
	  			busy(false);
		  	});
}

function syncTicket(syncData, callback) {
	// Need to parameterize this HOST ADDRESS
	var url = 'http://'+ serverHost +':' + serverPort + '/api/changerequests/dup';
	jQuery.post(url, {redmine_url:syncData.url},
			function (response) {
				callback(response);
			}, 'json').done(function(){
				busy(false);
			});
}

// Need to differentiate REQUEST data packet to handle more actions
chrome.extension.onMessage.addListener(
		function(request, sender, sendResponse) {
			console.log(request);
			console.log(sender);

			if (request.type == 'file.checkout') {
				var ticketId = jQuery('#cmotool-checkouts-panel').data("ticketId");
				var checkoutData = {
						ticket: ticketId,
						files: request.files
				};
				busy(true);
				checkoutFiles(checkoutData,function(updatedCheckoutData){
					console.log(updatedCheckoutData);
					if (updatedCheckoutData == null) {
						busy(false);
						return;
					}
					updateTicketCheckoutTable(updatedCheckoutData.files);				
				});
				
				sendResponse("Content DONE");
			}
		}
);
/**
 * Load extension settings
 */
storage.get('ServerConfig', function(config){
	serverHost = config.ServerConfig.host || 'localhost';
	serverPort = config.ServerConfig.port || '8080';
	
	jQuery(document).ready(function(){
		var matches = rgxTicket.exec(document.body.innerHTML);
		if (matches == null || matches.length == 0) {
			console.log('No ticket is found in HTML');
			return;
		}
		var ticketId = matches[0];
		// Retrieve checkout data from CMO-Server
		jQuery.get('http://'+ serverHost +':' + serverPort + '/api/changerequests/' + ticketId + '/files.json',
				function(checkoutData){
			updateChangeRequest(checkoutData.id, checkoutData.files);
		}, 'json').fail(function(jqXHR, textStatus, errorThrown){
			if (errorThrown == 'Not Found') {
				console.log('Ticket has not been registered with CMO');
				checkoutData = {
						id:ticketId,
						files:[]
				};
				updateChangeRequest(checkoutData.id, checkoutData.files);
				jQuery("#cmotool-checkouts-panel div.cmotool-message").html('Please sync ticket with CMO Server');
			}
		});
	});
});
chrome.storage.onChanged.addListener(function(config, areaName) {
	if (areaName == 'local') {
		serverHost = config.ServerConfig.host || 'localhost';
		serverPort = config.ServerConfig.port || '8080';
	}	
});